package com.example.springboottestgit.controller;

import com.example.springboottestgit.bean.BusinessException;
import com.example.springboottestgit.bean.CommonException;
import com.example.springboottestgit.bean.ResultMsg;
import com.example.springboottestgit.bean.vo.VideoVO;
import com.example.springboottestgit.enums.ExceptionCodeEnum;
import com.example.springboottestgit.service.InstanceVideoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.URLEncoder;

/**
 * @description:视频距离估算
 * @author: ZZZ
 */

@Slf4j
@RestController
@RequestMapping("/distance")
public class InstanceController {

    @Value("${distance.video.path}")
    private String distanceVideoPath;

    @Value("${distance.smoke.path}")
    private String distanceSmokePath;

    @Autowired
    private InstanceVideoService instanceVideoService;

    @GetMapping("/video/query")
    public ResultMsg<VideoVO> inviteTenderUpload(long id) {
        return ResultMsg.success(instanceVideoService.query(id));
    }

    @GetMapping("/file/download")
    public void fileDownload(HttpServletResponse response, String filePath) {
        if (!StringUtils.hasText(filePath)) {
            throw new CommonException(ExceptionCodeEnum.PARAMETER_ERROR.code, "参数 filePath 不能为空");
        }
        fileDownloadCommon(response, filePath);
        //return ResultMsg.success();
    }

    @GetMapping("/video/download")
    public void videoDownload(HttpServletResponse response, long id) {
        VideoVO vo = instanceVideoService.query(id);
        if (vo == null) {
            throw new CommonException(ExceptionCodeEnum.QUERY_NO_RESULT.code, "下载失败，查询无结果");
        }
        fileDownloadCommon(response, vo.getVideoDownloadPth());
        //return ResultMsg.success();
    }

    public void fileDownloadCommon(HttpServletResponse response, String filePath) {
        try {
            //获取要下载的文件
            File file = new File(filePath);
            if (!file.exists()) {
                throw new CommonException(ExceptionCodeEnum.QUERY_NO_RESULT.code, "文件不存在");
            }

            //设置响应的内容类型为二进制流，即文件类型
            response.setContentType("application/octet-stream");

            //设置文件名
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));

            //创建输入流
            FileInputStream inputStream = new FileInputStream(file);
            BufferedInputStream buffInputStream = new BufferedInputStream(inputStream);

            //创建输出流
            ServletOutputStream outputStream = response.getOutputStream();
            BufferedOutputStream buffOutputStream = new BufferedOutputStream(outputStream);

            //循环读取数据并写入到响应输出流中
            byte[] buffer = new byte[1024];
            int len = -1;
            while ((len = buffInputStream.read(buffer)) != -1) {
                buffOutputStream.write(buffer, 0, len);
            }
            //关闭流
            buffOutputStream.flush();
            buffOutputStream.close();
            outputStream.flush();
            outputStream.close();
            buffInputStream.close();
            inputStream.close();
        } catch (Exception e) {
            log.error("文件下载失败", e);
            throw new BusinessException(ExceptionCodeEnum.BUSINESS_ERROR.code, "文件下载失败");
        }

    }


    @PostMapping("/video/upload")
    public ResultMsg<VideoVO> inviteTenderUpload(@RequestParam("file") MultipartFile multipartFile, @RequestParam("videoType") String videoType) {

        String originalFilename = multipartFile.getOriginalFilename();
        if (!originalFilename.endsWith(".mp4")) {
            throw new CommonException(ExceptionCodeEnum.PARAMETER_ERROR.code, "请上传 mp4 文件格式");
        }

        if (!videoType.matches("[12]")) {
            throw new CommonException(ExceptionCodeEnum.PARAMETER_ERROR.code, "上传视频类型错误");
        }


        if (!instanceVideoService.modeStatus()) {
            throw new CommonException(ExceptionCodeEnum.MODE_BUSY.code, "程序忙碌中，请稍后再尝试一下");
        }

        //fileName = UUID.randomUUID() + suffixName;
        long timestamp = System.currentTimeMillis();

        String fileName = multipartFile.getOriginalFilename().replace(" ", "");
        String newFileName = fileName.substring(0, fileName.lastIndexOf(".")) + "-" + timestamp + fileName.substring(fileName.lastIndexOf("."));

        //videoType：1 室外 2室内
        String videoPath = videoType.equals("1") ? distanceVideoPath : distanceSmokePath;

        // xxx
        String prefixName = newFileName.substring(0, newFileName.lastIndexOf("."));
        // 获取文件的后缀名  .doc
        String suffixName = newFileName.substring(newFileName.lastIndexOf("."));

        // 上传后的路径
        String filePath = videoPath + newFileName;


        String videoDownloadPth = videoPath + "photo/" + prefixName + "/" + newFileName;

        String photoDownloadPth = videoPath + "photo/" + prefixName;


        // 构建上传路径
        File dest = new File(filePath);

        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        VideoVO vo = new VideoVO();
        try {
            // 保存文件
            log.info("========视频文件上传==========");
            multipartFile.transferTo(dest);

            vo.setId(timestamp);
            vo.setStatus(0);
            vo.setVideoType(videoType);
            vo.setFileName(prefixName);
            vo.setVideoDownloadPth(videoDownloadPth);
            vo.setPhotoDownloadPth(photoDownloadPth);
            //视频上传保持
            instanceVideoService.save(vo);
            //调用视频距离估算模型
            instanceVideoService.videoMode(timestamp);
            //视频解析
            //instanceVideoService.videoAnalysis(timestamp);

        } catch (Exception e) {
            log.error("文件上传失败", e);
            throw new BusinessException(ExceptionCodeEnum.BUSINESS_ERROR.code, "文件上传失败");
        }
        return ResultMsg.success(vo);
    }
}




